<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input placeholder="请输入内容"
                    clearable
                    @clear="getUserList"
                    v-model="queryData.query"
                    class="input-with-select">
            <el-button @click="getUserList"
                       slot="append"
                       icon="el-icon-search"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary"
                     @click="addDialogVisible=true">添加用户</el-button>
        </el-col>
      </el-row>
      <el-table :data="users"
                border
                stripe>
        <el-table-column type="index"
                         label="#"
                         width="50px"></el-table-column>
        <el-table-column label="姓名"
                         prop="username"></el-table-column>
        <el-table-column label="邮箱"
                         prop="email"></el-table-column>
        <el-table-column label="电话"
                         prop="mobile"></el-table-column>
        <el-table-column label="角色"
                         prop="role_name"></el-table-column>
        <el-table-column prop="role_name"
                         label="状态">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state"
                       active-color="#13ce66"
                       @change="switchChange(scope.row)"
                       inactive-color="#ff4949">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column prop="date"
                         label="操作"
                         width="200px">
          <template slot-scope="scope">
            <el-tooltip :enterable="false"
                        class="item"
                        effect="dark"
                        content="添加"
                        placement="top">
              <el-button size="mini"
                         type="primary"
                         icon="el-icon-edit"
                         @click="showEditDialog(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip :enterable="false"
                        class="item"
                        effect="dark"
                        content="删除"
                        placement="top">
              <el-button size="mini"
                         type="danger"
                         icon="el-icon-delete"
                         @click="removeUser(scope.row.id)"></el-button>
            </el-tooltip>
            <el-tooltip :enterable="false"
                        class="item"
                        effect="dark"
                        content="分配角色"
                        placement="top">
              <el-button @click="showSetRoles(scope.row)"
                         size="mini"
                         type="warning"
                         icon="el-icon-setting"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination @size-change="handleSizeChange"
                     @current-change="handleCurrentChange"
                     :current-page="queryData.pagenum"
                     :page-sizes="[2,6 ,8 , 10]"
                     :page-size="queryData.pagesize"
                     layout="total, sizes, prev, pager, next, jumper"
                     :total="total">
      </el-pagination>
    </el-card>
    <el-dialog @close="dialogClose"
               title="添加用户"
               :visible.sync="addDialogVisible"
               width="50%">
      <el-form ref="addUserFormRef"
               :model="addUserForm"
               :rules="addUserFormRules"
               label-width="80px">
        <el-form-item label="用户名"
                      prop="username">
          <el-input v-model="addUserForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码"
                      prop="password">
          <el-input v-model="addUserForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱"
                      prop="email">
          <el-input v-model="addUserForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机"
                      prop="mobile">
          <el-input v-model="addUserForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer"
            class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary"
                   @click="submitAddForm">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改用户表单 -->
    <el-dialog @close="editDialogClose"
               title="修改用户"
               :visible.sync="editDialogVisible"
               width="50%">
      <el-form ref="editUserForm"
               :rules="editUserRules"
               :model="editUserForm"
               label-width="80px">
        <el-form-item label="用户名:">
          <el-input disabled
                    v-model="editUserForm.username"></el-input>
        </el-form-item>
        <el-form-item prop="email"
                      label="邮箱:">
          <el-input v-model="editUserForm.email"></el-input>
        </el-form-item>
        <el-form-item prop="mobile"
                      label="手机号:">
          <el-input v-model="editUserForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer"
            class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary"
                   @click="submitEditUser">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog @close="closeSetRoles"
               title="分配角色"
               :visible.sync="setRolesDialogVisible"
               width="50%">
      <p>当前的用户：{{currentUser.username}}</p>
      <p>当前的角色：{{currentUser.role_name}}</p>
      <div>
        分配新角色：
        <el-select v-model="selectValue"
                   placeholder="请选择角色">
          <el-option v-for="item in roles"
                     :key="item.id"
                     :label="item.roleName"
                     :value="item.id">
          </el-option>
        </el-select>
      </div>
      <span slot="footer"
            class="dialog-footer">
        <el-button @click="setRolesDialogVisible = false">取消</el-button>
        <el-button type="primary"
                   @click="submitSetRoles">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'user',
  data () {
    const checkEmail = (rule, value, callback) => {
      const reg = /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/
      if (reg.test(value)) {
        return callback()
      }
      return callback(new Error('不合法'))
    }
    const checkMobile = (rule, value, callback) => {
      const reg = /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/
      if (reg.test(value)) {
        return callback()
      }
      return callback(new Error('手机号不合法'))
    }
    return {
      queryData: {
        query: '',
        pagenum: 1,
        pagesize: 2
      },
      users: [],
      total: 0,
      addDialogVisible: false,
      addUserForm: {
        username: '年轻人，不讲舞德',
        password: '123333',
        email: 'qq@qq.com',
        mobile: 13089898983
      },
      addUserFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 2, max: 7, message: '长度在 2 到 7 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 2, max: 7, message: '长度在 2 到 7 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      // 控制编辑对话框
      editDialogVisible: false,
      // 编辑用户表单数据
      editUserForm: {
        username: '第三方',
        mobile: '18911111111',
        email: 'saasd@qq.com'
      },
      editUserRules: {
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          // validator: function 进行自定义校验规则
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      setRolesDialogVisible: false,
      currentUser: {},
      roles: [],
      selectValue: ''
    }
  },

  created () {
    this.getUserList()
  },

  methods: {
    async getUserList () {
      const { data: res } = await this.$axios.get('users', {
        params: this.queryData
      })
      if (res.meta.status !== 200) return this.$message.error('获取数据失败，请检查代码')
      this.users = res.data.users
      this.total = res.data.total
    },
    handleSizeChange (val) {
      this.queryData.pagesize = val
      this.getUserList()
    },
    handleCurrentChange (val) {
      this.queryData.pagenum = val
      this.getUserList()
    },
    async switchChange (item) {
      const { data: res } = await this.$axios.put(`users/${item.id}/state/${item.mg_state}`)
      if (res.meta.status !== 200) {
        this.$message.error('修改失败')
        item.mg_state = !item.mg_state
        return
      }
      this.$message.success('修改成功')
    },
    dialogClose () {
      this.$refs.addUserFormRef.resetFields()
    },
    submitAddForm () {
      this.$refs.addUserFormRef.validate(async flag => {
        if (!flag) return
        // 请求调试
        // 请求url
        // 请求method
        // 请求headers
        // 请求参数
        const { data: res } = await this.$axios.post('users', this.addUserForm)
        if (res.meta.status !== 201) return this.$message.error('创建失败')
        this.$message.success('创建成功')
        // 关闭对话框
        this.addDialogVisible = false
        // 重新获取列表数据
        this.getUserList()
      })
    },
    showEditDialog (item) {
      this.editUserForm = item
      this.editDialogVisible = true
    },
    // 监听编辑对话框关闭
    editDialogClose () {
      this.$refs.editUserForm.resetFields()
    },
    // 提交编辑用户
    submitEditUser () {
      this.$refs.editUserForm.validate(async flag => {
        if (!flag) return
        const { data: res } = await this.$axios.put('users/' + this.editUserForm.id, this.addUserForm)
        if (res.meta.status !== 200) return this.$message.error('更新失败')
        this.$message.success('更新成功')
        this.editDialogVisible = false
        this.getUserList()
      })
    },
    removeUser (id) {
      this.$confirm('删除是否,继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { data: res } = await this.$axios.delete('users/' + id)
        if (res.meta.status !== 200) return this.$message.error('删除失败')
        this.$message.success('删除成功')
        this.getUserList()
      }).catch(() => {
        // this.$message({
        //   type: 'info',
        //   message: '已取消删除'
        this.$message('已取消删除')
      })
    },
    async showSetRoles (row) {
      this.setRolesDialogVisible = true
      this.currentUser = row
      const { data: res } = await this.$axios.get('roles')
      if (res.meta.status !== 200) return this.$message.error('获取失败')
      this.roles = res.data
    },
    async submitSetRoles () {
      if (this.selectValue === '') return this.$message.error('亲选择新角色')
      const { data: res } = await this.$axios.put('users/' + this.currentUser.id + '/role', {
        rid: this.selectValue
      })
      if (res.meta.status !== 200) return this.$message.error('设置失败')
      this.setRolesDialogVisible = false
      this.getUserList()
      this.$message.success('分配成功')
    },
    closeSetRoles () {
      this.selectValue = ''
    }
  }
}
</script>

<style scoped lang='less'>
</style>
